import { useRef, useState } from 'react';

import { useAntdTable, useRequest } from 'ahooks';
import { Button, Input, Select, Space, Table, Tag, Tooltip } from 'antd';

import Filter from '@/components/filter';
import Text from '@/components/text';

import { usePermission } from '@/auth';
import { TimeSort } from '@/enum';
import { StatusObj } from '@/enum/product';
import { orgUserInfoVoPage } from '@/services/base/yonghuguanlixitongyonghujiekou';
import {
  equMaintainRecordPage,
  equMaintainRecordStatistics
} from '@/services/bizApi/shebaobaoyangjilujiekou';

import Dispose, { DisposeRef } from './dispose';
import Edit, { EditRef } from './edit';

/** 该模块增删改查对象 */
export type BizObject = BIZAPI.EquMaintainRecordEntity;

const Page: React.FC = () => {
  const permission = usePermission();
  const edit = useRef<EditRef>(null);
  const dispose = useRef<DisposeRef>(null);
  const [filter] = Filter.useForm();
  const [statisticsCondition, setStatisticsCondition] = useState('');

  const userInfo = useRequest(
    async () => {
      const res = await orgUserInfoVoPage({ page: 1, size: 1000 });

      return res?.data?.records;
    },
    {
      refreshDeps: []
    }
  );

  const statistic = useRequest(
    async () => {
      const res = await equMaintainRecordStatistics();

      return res?.data || {};
    },
    {
      refreshDeps: []
    }
  );

  const table = useAntdTable(
    async ({ current, pageSize }, { id, ...formData }) => {
      const res = await equMaintainRecordPage({
        ...formData,
        ...id,
        statisticsCondition,
        page: current,
        size: pageSize,
        timeSort: TimeSort.倒序
      });

      return {
        list: res.data?.records || [],
        total: res.data?.total || 0
      };
    },
    {
      form: filter
    }
  );

  const onSearch = () => {
    setStatisticsCondition('');
    table.search.submit();
  };

  const onReset = () => {
    table.search.reset();
  };

  const statisticSearch = (condition: string) => () => {
    table.search.reset();
    if (statisticsCondition === condition) {
      setStatisticsCondition('');
    } else {
      setStatisticsCondition(condition);
    }
    table.search.submit();
  };

  return (
    <>
      {/**统计 */}
      <Space size={16} style={{ marginBottom: '20px', fontWeight: 'bold', cursor: 'pointer' }}>
        <div>
          <span
            onClick={statisticSearch('1')}
            style={{ color: statisticsCondition === '1' ? 'var(--ant-color-primary)' : '' }}
          >
            本月计划保养总数：
          </span>
          <Text onClick={statisticSearch('1')} style={{ marginRight: '10px' }}>
            {statistic?.data?.value1 || 0}
          </Text>
          <Tag
            onClick={statisticSearch('2')}
            style={{ cursor: 'pointer' }}
            color={statisticsCondition === '2' ? 'gold' : ''}
          >
            一级：<Text>{statistic?.data?.value2 || 0}</Text>
          </Tag>
          <Tag
            onClick={statisticSearch('3')}
            style={{ cursor: 'pointer' }}
            color={statisticsCondition === '3' ? 'gold' : ''}
          >
            二级：<Text>{statistic?.data?.value3 || 0}</Text>
          </Tag>
          <Tag
            onClick={statisticSearch('4')}
            style={{ cursor: 'pointer' }}
            color={statisticsCondition === '4' ? 'gold' : ''}
          >
            三级：<Text>{statistic?.data?.value4 || 0}</Text>
          </Tag>
        </div>
        <div>
          <span
            onClick={statisticSearch('5')}
            style={{ color: statisticsCondition === '5' ? 'var(--ant-color-primary)' : '' }}
          >
            本月未完成数：
          </span>
          <Text style={{ marginRight: '10px' }}>{statistic?.data?.value5 || 0}</Text>
          <Tag
            onClick={statisticSearch('6')}
            style={{ cursor: 'pointer' }}
            color={statisticsCondition === '6' ? 'gold' : ''}
          >
            一级：<Text>{statistic?.data?.value6 || 0}</Text>
          </Tag>
          <Tag
            onClick={statisticSearch('7')}
            style={{ cursor: 'pointer' }}
            color={statisticsCondition === '7' ? 'gold' : ''}
          >
            二级：<Text>{statistic?.data?.value7 || 0}</Text>
          </Tag>
          <Tag
            onClick={statisticSearch('8')}
            style={{ cursor: 'pointer' }}
            color={statisticsCondition === '8' ? 'gold' : ''}
          >
            三级：<Text>{statistic?.data?.value8 || 0}</Text>
          </Tag>
        </div>
      </Space>

      {/* 筛选 */}
      <Filter onFinish={onSearch} form={filter}>
        <Filter.Item name="equipmentName">
          <Input
            style={{
              width: 160
            }}
            placeholder="请输入设备名称"
          />
        </Filter.Item>
        <Filter.Item name="equipmentCode">
          <Input
            style={{
              width: 160
            }}
            placeholder="请输入设备编号"
          />
        </Filter.Item>
        <Filter.Item name="dutyUserId">
          <Select
            style={{
              width: 160
            }}
            allowClear
            placeholder="请选择责任人"
            showSearch={true}
            optionFilterProp="label"
            options={
              userInfo?.data?.map((item) => {
                return {
                  label: item?.fullName,
                  value: item?.id
                };
              }) || []
            }
          />
        </Filter.Item>
        <Filter.Item name="maintainGrade">
          <Select
            style={{
              width: 160
            }}
            allowClear
            placeholder="请选择等级"
            options={[
              {
                label: '一级',
                value: '一级'
              },
              {
                label: '二级',
                value: '二级'
              },
              {
                label: '三级',
                value: '三级'
              }
            ]}
          />
        </Filter.Item>
        <Filter.Item name="status">
          <Select
            style={{
              width: 160
            }}
            allowClear
            placeholder="请选择状态"
            options={[
              {
                label: '待处理',
                value: 1
              },
              {
                label: '已完成',
                value: 3
              }
            ]}
          />
        </Filter.Item>
        <Filter.Item>
          <Button htmlType="submit" disabled={table.loading}>
            搜索
          </Button>
        </Filter.Item>

        <Filter.Item>
          <Button onClick={onReset} disabled={table.loading}>
            重置
          </Button>
        </Filter.Item>
      </Filter>
      {/* end 筛选 */}

      {/* 表格 */}
      <Table<BizObject>
        size="small"
        columns={[
          {
            title: '序号',
            dataIndex: 'index',
            align: 'center',
            width: 60,
            render: (_text, _record, index) => index + 1
          },
          {
            title: '生产站点',
            dataIndex: 'productionSite'
          },
          {
            title: '工艺段',
            dataIndex: 'processSection'
          },
          {
            title: '设备名称',
            dataIndex: 'equipmentName'
          },
          {
            title: '状态',
            dataIndex: 'status',
            render: (v) => {
              const obj = StatusObj.get(v);

              if (obj) {
                return <Tag color={obj.color}>{obj.text}</Tag>;
              }

              return emptyText;
            }
          },
          {
            title: '维护保养内容',
            dataIndex: 'maintainContent',
            width: 300,
            ellipsis: true,
            render: (text) => (
              <Tooltip placement="top" title={text} arrow={true}>
                <div
                  style={{
                    width: '300px',
                    wordBreak: 'break-all',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap'
                  }}
                >
                  {text}
                </div>
              </Tooltip>
            )
          },
          // {
          //   title: '设备编号',
          //   dataIndex: 'equipmentCode'
          // },
          {
            title: '设备数量',
            dataIndex: 'equipmentCount'
          },
          {
            title: '等级',
            dataIndex: 'maintainGrade'
          },
          {
            title: '责任人',
            dataIndex: 'dutyUserName'
          },
          // {
          //   title: '备注',
          //   dataIndex: 'maintainRemark'
          // },
          {
            title: '处置情况',
            dataIndex: 'handleSituation'
          },
          {
            title: '操作',
            fixed: 'right',
            align: 'center',
            render: (_, row) => {
              return (
                <Text.Space>
                  {/* {permission.check() &&
                    row?.status === 1 &&
                    row?.dutyUserId === store?.user?.id && ( */}
                  <Text
                    onClick={() => {
                      dispose.current?.open({
                        rowData: row,
                        onSuccess: () => {
                          table.refresh();
                        }
                      });
                    }}
                    type="primary"
                  >
                    处置
                  </Text>
                  {/* )} */}
                  {permission.check() && (
                    <Text
                      onClick={() => {
                        edit.current?.open({
                          type: 'detail',
                          rowData: row,
                          onSuccess: () => {
                            table.refresh();
                          }
                        });
                      }}
                      type="primary"
                    >
                      详情
                    </Text>
                  )}
                </Text.Space>
              );
            }
          }
        ]}
        scroll={{
          x: 'max-content'
        }}
        rowKey="id"
        bordered
        {...table.tableProps}
        pagination={{
          ...table.tableProps.pagination,
          showTotal: (total) => `共 ${total} 条`,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50', '100']
        }}
      />
      {/* end表格 */}

      <Edit ref={edit} />
      <Dispose ref={dispose} />
    </>
  );
};

export default Page;
